const logger = require('koa-logger');
const {logPath} = require('../config');
const fs = require('fs');
const path = require('path');

module.exports = server => {
	server.use(async (ctx, next) => {
		const start = new Date()
		await next()
		const ms = new Date() - start;
		let requestdata = '';
		if (ctx.method === 'post' || ctx.method === 'POST') {
			requestdata = JSON.stringify(ctx.request.fields)
		} else {
			if (ctx.query) {
				requestdata = JSON.stringify(ctx.query)
			} else {
				requestdata = JSON.stringify(ctx.params)
			}

		}

		function add0(m) {
			return m < 10 ? '0' + m : m
		}
		/*将时间戳转成 全时间格式转换成  2011-3-16 16:50 */
		var time = new Date();
		var y = time.getFullYear();
		var m = time.getMonth() + 1;
		var d = time.getDate();
		var h = time.getHours();
		var mm = time.getMinutes();
		var s = time.getSeconds();
		const day ='log'+ y + '.' + add0(m) + '.' + add0(d) + '.txt'
		const nowTime = y + '-' + add0(m) + '-' + add0(d) + ' ' + add0(h) + ':' + add0(mm) + ':' + add0(s);
		 

		await new Promise((resolve, reject) => {
			fs.appendFile(path.resolve(logPath, day), `[${nowTime}]  ${ctx.method}  ${ctx.url} ${ms}ms  \r\n ${requestdata}\r\n\r\n`, err => {				 
				resolve();
			})
		})
	})
}
